package com.easy.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadFileUtil {
    private static final String UPLOAD_DRI = "D:\\Desktop\\mycode\\java\\myWarehouse\\src\\main\\resources\\images\\";
    private static final Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);

    static {
        File file = new File(UPLOAD_DRI);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static String uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("Uploaded file is empty");
        }

        // 获取原文件名和后缀名
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new IllegalArgumentException("File name cannot be null");
        }
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));

        // 生成新的文件名，不带后缀
        String newBaseName = UUID.randomUUID().toString();
        String newFileName = newBaseName + fileExtension;

        // 保存文件
        File newFile = new File(UPLOAD_DRI + newFileName);
        try {
            file.transferTo(newFile);
            logger.info("File uploaded successfully: {}", newFile.getAbsolutePath());
        } catch (IOException e) {
            logger.error("File upload failed", e);
            throw new RuntimeException("File upload failed", e);
        }

        // 返回新的文件名，包括后缀
        return newFileName;
    }
}
